﻿using System;
using System.Collections.Generic;
using System.Text;
using He.Common;
using LitJson;

namespace He.API.WeiXin
{
    public class JsapiTicket
    {
        private int _errcode;
        private string _errmsg;
        private string _ticket;
        private int _expires_in;

        public int errcode
        {
            get
            {
                return this._errcode;
            }
            set
            {
                this._errcode = value;
            }
        }

        public string errmsg
        {
            get
            {
                return this._errmsg;
            }
            set
            {
                this._errmsg = value;
            }
        }

        public string ticket
        {
            get
            {
                return this._ticket;
            }
            set
            {
                this._ticket = value;
            }
        }

        public int expires_in
        {
            get
            {
                return this._expires_in;
            }
            set
            {
                this._expires_in = value;
            }
        }


        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="noncestr"></param>
        /// <param name="timestamp"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSignature(string noncestr, string timestamp, string url)
        {
            string jsapi_ticket = GetTicket(CheckSignature.GetAccessToken());
            return CryptoHelper.SHA1(string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url));
        }

        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetTicket(string accessToken)
        {
            if (DateTime.Compare(DateTime.Now, Config.wx_config.jsapi_ticket_expires_in) > 0 || string.IsNullOrEmpty(Config.wx_config.jsapi_ticket))
            {
                JsapiTicket ticket = JsonMapper.ToObject<JsapiTicket>(HttpHelper.HttpGet(string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", accessToken)));
                if (ticket.errcode == 0)
                {
                    Config.wx_config.jsapi_ticket = ticket.ticket;
                    Config.wx_config.jsapi_ticket_expires_in = DateTime.Now.AddSeconds((double)ticket.expires_in);
                    new BLL.config().SaveConfig<Model.wx_config>(Config.wx_config, SysKeys.WEIXIN_CONFIG_PATH);
                    return ticket.ticket;
                }
                return ticket.errmsg;
               
            }
            return Config.wx_config.jsapi_ticket;
        }
    }

}
